package com.yida.system.controller;

import com.yida.common.core.domain.R;
import com.yida.common.core.exception.ServiceException;
import com.yida.common.core.utils.StringUtils;
import com.yida.common.core.utils.poi.ExcelUtil;
import com.yida.common.core.web.controller.BaseController;
import com.yida.common.core.web.domain.AjaxResult;
import com.yida.common.core.web.page.TableDataInfo;
import com.yida.common.log.annotation.Log;
import com.yida.common.log.enums.BusinessType;
import com.yida.common.security.annotation.InnerAuth;
import com.yida.common.security.annotation.RequiresPermissions;
import com.yida.common.security.utils.SecurityUtils;
import com.yida.system.api.domain.SysArea;
import com.yida.system.api.domain.SysUser;
import com.yida.system.domain.SysUserArea;
import com.yida.system.service.ISysAreaService;
import com.yida.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 地区管理Controller
 * 
 * @author hmh
 * @date 2022-11-08
 */
@RestController
@RequestMapping("/area")
public class SysAreaController extends BaseController {
    @Autowired
    private ISysAreaService sysAreaService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询地区管理列表
     */
    @RequiresPermissions("system:area:list")
    @GetMapping("/list")
    public AjaxResult list(SysArea sysArea) {
        List<SysArea> list = sysAreaService.selectSysAreaList(sysArea);
        return AjaxResult.success(list);
    }

    /**
     * 导出地区管理列表
     */
    @RequiresPermissions("system:area:export")
    @Log(title = "地区管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysArea sysArea) {
        List<SysArea> list = sysAreaService.selectSysAreaList(sysArea);
        ExcelUtil<SysArea> util = new ExcelUtil<SysArea>(SysArea.class);
        util.exportExcel(response, list, "地区管理数据");
    }

    /**
     * 获取地区管理详细信息
     */
    @RequiresPermissions("system:area:query")
    @GetMapping(value = "/{areaId}")
    public AjaxResult getInfo(@PathVariable("areaId") Long areaId) {
        return AjaxResult.success(sysAreaService.selectSysAreaByAreaId(areaId));
    }

    /**
     * 根据地区ID获取地区树 20221111 hmh
     */
    // @RequiresPermissions("system:area:query")
    @GetMapping(value = "/tree/{areaIds}")
    public AjaxResult getAreaTreeInfoByAreaId(@PathVariable Long[] areaIds) {
        // 1
        return AjaxResult.success(sysAreaService.selectAreaTreeByAreaIdArry(areaIds));
    }

    /**
     * 根据地区编号组获取对于地区下拉列表，及街道数据 20221111 hmh
     */
    @GetMapping(value = "/areaStreet/{areaIds}")
    public AjaxResult getAreaStreetInfoByAreaId(@PathVariable String areaIds) {
        // if(SecurityUtils.getUserId()==1L) {
        // areaIds = "1";
        // }
        return AjaxResult.success(sysAreaService.getAreaStreetInfoByAreaId(areaIds));
    }

    /**
     * 根据地区编号组获取对于地区下拉列表，及街道数据 20221213 hmh
     */
    @GetMapping(value = "/tree/areas/{areaIds}")
    public AjaxResult getAreaTreeInfoByAreaId(@PathVariable String areaIds) {
        if (SecurityUtils.getUserId() == 1L) {
            areaIds = "1";
        }
        return AjaxResult.success(sysAreaService.getAreaTreeInfoByAreaIds(areaIds));
    }

    /**
     * 根据查询地区组信息 20221111 hmh
     */
    @GetMapping(value = "/array")
    public AjaxResult getAreaByAreaIds() {
        return AjaxResult.success(sysAreaService.selectAreaInfoByAreaType(2));
    }

    /**
     * 新增地区管理
     */
    @RequiresPermissions("system:area:add")
    @Log(title = "地区管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysArea sysArea) {
        // 判定地区名是否重复
        if (sysAreaService.checkAreaName(sysArea)) {
            throw new ServiceException(sysArea.getAreaName() + "已经存在，不能重复添加！");
        }
        sysArea.setCreateBy(SecurityUtils.getUsername());
        return toAjax(sysAreaService.insertSysArea(sysArea));
    }

    /**
     * 修改地区管理
     */
    @RequiresPermissions("system:area:edit")
    @Log(title = "地区管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysArea sysArea) {
        // 判断是否能修改
        sysAreaService.checkAreaAllowed(sysArea);
        // 判定地区名是否重复
        if (sysAreaService.checkAreaName(sysArea)) {
            throw new ServiceException(sysArea.getAreaName() + "已经存在，与当前操作编号冲突，请修改后提交！");
        }
        sysArea.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysAreaService.updateSysArea(sysArea));
    }

    /**
     * 状态切换
     */
    @RequiresPermissions("system:area:edit")
    @Log(title = "地区管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysArea sysArea) {
        // 判断是否能修改
        sysAreaService.checkAreaAllowed(sysArea);
        sysArea.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysAreaService.updateSysArea(sysArea));
    }

    /**
     * 删除地区管理
     */
    @RequiresPermissions("system:area:remove")
    @Log(title = "地区管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{areaIds}")
    public AjaxResult remove(@PathVariable Long[] areaIds) {
        return toAjax(sysAreaService.deleteSysAreaByAreaIds(areaIds));
    }

    /**
     * 查看当前地区已绑定用户
     */
    @RequiresPermissions("system:area:list")
    @GetMapping("/bindUser/allocatedList")
    public TableDataInfo allocatedList(SysUser user) {
        sysAreaService.checkAreaAllowed(user.getAreaId());
        startPage();
        List<SysUser> list = userService.selectAllocatedAreaList(user);
        return getDataTable(listChangeToMap(list));
    }

    /**
     * 查看当前地区未绑定用户
     */
    @RequiresPermissions("system:area:list")
    @GetMapping("/bindUser/unallocatedList")
    public TableDataInfo unallocatedList(SysUser user) {
        sysAreaService.checkAreaAllowed(user.getAreaId());
        startPage();
        List<SysUser> list = userService.selectUnallocatedAreaList(user);
        return getDataTable(listChangeToMap(list));
    }

    /**
     * list转Map
     * 
     * @param list 用户集合
     * @return
     */
    private List<Map<String, Object>> listChangeToMap(List<SysUser> list) {
        if (StringUtils.isEmpty(list) && list.size() == 0) {
            return new ArrayList<Map<String, Object>>();
        }
        List<Map<String, Object>> mapList = list.stream().map(su -> {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userId", su.getUserId());
            map.put("userName", su.getUserName());
            map.put("realName", su.getRealName());
            return map;
        }).collect(Collectors.toList());
        return mapList;
    }

    /**
     * 解绑地区
     */
    @RequiresPermissions("system:area:edit")
    @Log(title = "地区管理", businessType = BusinessType.GRANT)
    @PutMapping("/bindUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody SysUserArea userArea) {
        sysAreaService.checkAreaAllowed(userArea.getAreaId());
        return toAjax(sysAreaService.deleteBindUser(userArea));
    }

    /**
     * 批量取消地区绑定用户
     */
    @RequiresPermissions("system:area:edit")
    @Log(title = "地区管理", businessType = BusinessType.GRANT)
    @PutMapping("/bindUser/cancelAll")
    public AjaxResult cancelBindUserAll(@RequestParam("areaId") Long areaId, @RequestParam("userIds") Long[] userIds) {
        sysAreaService.checkAreaAllowed(areaId);
        return toAjax(sysAreaService.deleteBindUsers(areaId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @RequiresPermissions("system:area:edit")
    @Log(title = "地区管理", businessType = BusinessType.GRANT)
    @PutMapping("/bindUser/selectAll")
    public AjaxResult selectBindUserAll(@RequestParam("areaId") Long areaId, @RequestParam("userIds") Long[] userIds) {
        sysAreaService.checkAreaAllowed(areaId);
        return toAjax(sysAreaService.insertUserAreas(areaId, userIds));
    }

    /**
     * 获取vote地区详细信息
     */
    @InnerAuth
    @GetMapping(value = "/vote/area/{areaId}")
    public R<SysArea> getVoteAreaInfo(@PathVariable("areaId") Long areaId) {
        SysArea sa = sysAreaService.selectSysAreaByAreaId(areaId);
        if (StringUtils.isNull(sa)) {
            return R.fail("获取投票地区信息失败！");
        }
        return R.ok(sa, "获取投票地区信息成功！");
    }

}
